package com.wp.leetCode;

import java.util.Stack;

/**
 * Created by 王萍 on 2017/8/2 0002.
 */

/**
 * Evaluate the value of an arithmetic expression in Reverse Polish Notation.
 Valid operators are+,-,*,/. Each operand may be an integer or another expression.
 Some examples:

 方法：遇到一个非数字字符，即+，-，*，/，便从栈中取出两个数做一次运算，将运算结果再放入栈中。最后栈中只剩一个数字，就是所求的结果。
 */
public class 计算算术表达式的值 {
    public static void main(String[] args) {

        //   ["2", "1", "+", "3", "*"]
        String[] str = {"2", "1", "+", "3", "*"};
        System.out.println(evalRPN(str));

        //["4", "13", "5", "/", "+"]
        String[] str2 = {"4", "13", "5", "/", "+"};
        System.out.println(evalRPN(str2));
    }

    public static int evalRPN(String[] tokens) {

        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            try {
                int num = Integer.parseInt(token);
                stack.push(num);
            } catch (Exception e) {
                int after = stack.pop();
                int before = stack.pop();
                stack.add(getResult(before, after, token));
            }
        }
        return stack.pop();
    }

    public static int getResult(int before, int after, String token) {
        switch (token) {
            case "+":
                return before + after;
            case "-":
                return before - after;
            case "*":
                return before * after;
            case "/":
                return before / after;
            default:
                return 0;
        }
    }
}
